package edu.iscas.appcheckclient.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;

import edu.iscas.appcheckclient.Adpater.TabsPagerAdapter;
import edu.iscas.appcheckclient.BuildConfig;
import edu.iscas.appcheckclient.R;
import edu.iscas.appcheckclient.model.actions.Request;
import edu.iscas.appcheckclient.service.RecordService;
import edu.iscas.appcheckclient.service.network.RequestManager;
import edu.iscas.appcheckclient.service.network.Uploader;

public class ResultsActivity extends AppCompatActivity implements android.support.v7.app.ActionBar.TabListener{

    private static final String TAG = ResultsActivity.class.getSimpleName();
    protected Request request;
    protected static RequestManager requestManager;
    protected boolean isUploadable;

    // Tab titles
    private String[] tabs = {"Action", "HttpResponse", "Location"};
    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private android.support.v7.app.ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String requestStr = getIntent().getStringExtra("request");

        if(requestStr != null){
            this.request = Request.fromJSON(requestStr);
        }
        this.isUploadable = getIntent().getBooleanExtra("uploadable", false);

        actionBar = getSupportActionBar();
        setContentView(R.layout.activity_results);

        //init tabs
        viewPager = (ViewPager)findViewById(R.id.pg_actions);
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), request);
        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(android.support.v7.app.ActionBar.NAVIGATION_MODE_TABS);
        for(String tab_name : tabs){
            actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
        }

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_results, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_item_sendToServer:

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                final EditText editText = new EditText(this);
                editText.setText("http://" + BuildConfig.IP + ":" + BuildConfig.PORT);
                alertDialogBuilder.setView(editText);
                alertDialogBuilder.setMessage("Please enter the address of the server to upload");

                alertDialogBuilder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uploader uploader = Uploader.getInstance(getApplicationContext(), editText.getText().toString());

                        uploader.uploadTest(ResultsActivity.this.getResources().getString(R.string.upload_address),request, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d(TAG + " onResponse", response);
                                Toast.makeText(ResultsActivity.this, "Upload test successfully.", Toast.LENGTH_SHORT).show();
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.e(TAG + " onErrorResponse", "Error:" + error.getMessage());
                                Toast.makeText(ResultsActivity.this, "Upload test failed.", Toast.LENGTH_SHORT).show();
                                error.printStackTrace();
                            }
                        });
                    }
                });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                alertDialog.show();
                break;
            case R.id.menu_item_resume_record:
                this.finish();
                //resume recording
                RecordService.resumeRecording();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(android.support.v7.app.ActionBar.Tab tab, FragmentTransaction ft) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(android.support.v7.app.ActionBar.Tab tab, FragmentTransaction ft) {

    }

    @Override
    public void onTabReselected(android.support.v7.app.ActionBar.Tab tab, FragmentTransaction ft) {

    }

}
